<template>
  <div class="content-text" ref="contentRef" :style="{'lineClamp':isExpand?'unset':'3'}">{{ content }}</div>
  <div class="expand" v-if="canClamped" @click="toggleExpand()">{{ isExpand?'收起':'展开' }}</div>
</template>
<script setup>
const props = defineProps({
  content: {
    type: String,
    default: ''
  },
  lineClamp: {
    type: Number,
    default: 3
  }
})
const contentRef = ref(null)
const isExpand = ref(false)
const canClamped = ref(false) // 是否支持折叠
const toggleExpand = () => {
  isExpand.value = !isExpand.value
}
// 检测是否需要折叠
const checkClamp = () => {
  nextTick(() => {
    if (!contentRef.value) return
    const lineHeight = parseInt(getComputedStyle(contentRef.value).lineHeight) // 行高
    const lineNum = props.lineClamp.value || 3 // 默认3行
    const maxHeight = lineHeight * lineNum
    canClamped.value = contentRef.value.scrollHeight > maxHeight
  })
}
onMounted(() => {
   checkClamp()
  // 监听窗口变化重新检测
  window.addEventListener('resize', checkClamp)
})
</script>
<style lang="scss" scoped>
    .content-text {
      line-height: 1.5;
      white-space: pre-wrap;
      word-break: break-all;
      overflow: hidden;
      text-overflow: ellipsis;
      -webkit-line-clamp: 3;
      line-clamp: 3;
      display: -webkit-box;
      -webkit-box-orient: vertical;
    }
    .expand {
      color: dodgerblue;
      cursor: pointer;
      margin-top: 10px;
    }
</style>